package com.zhht.htzx.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhht.htzx.model.Order;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 订单管理工具类
 */
public class OrderManager {
    
    private static final String PREF_NAME = "order_manager";
    private static final String KEY_ORDERS = "orders";
    
    private static OrderManager instance;
    private SharedPreferences preferences;
    private Gson gson;
    
    private OrderManager(Context context) {
        preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }
    
    public static synchronized OrderManager getInstance(Context context) {
        if (instance == null) {
            instance = new OrderManager(context.getApplicationContext());
        }
        return instance;
    }
    
    /**
     * 保存订单
     */
    public void saveOrder(Order order) {
        List<Order> orders = getAllOrders();
        
        // 检查是否已存在相同订单ID的订单
        boolean exists = false;
        for (int i = 0; i < orders.size(); i++) {
            if (TextUtils.equals(orders.get(i).getOrderId(), order.getOrderId())) {
                orders.set(i, order);
                exists = true;
                break;
            }
        }
        
        if (!exists) {
            orders.add(order);
        }
        
        saveOrders(orders);
    }
    
    /**
     * 获取所有订单
     */
    public List<Order> getAllOrders() {
        String json = preferences.getString(KEY_ORDERS, "[]");
        Type type = new TypeToken<List<Order>>(){}.getType();
        List<Order> orders = gson.fromJson(json, type);
        return orders != null ? orders : new ArrayList<>();
    }
    
    /**
     * 根据用户ID获取订单列表
     */
    public List<Order> getOrdersByUserId(String userId) {
        List<Order> allOrders = getAllOrders();
        List<Order> userOrders = new ArrayList<>();
        
        for (Order order : allOrders) {
            if (TextUtils.equals(order.getUserId(), userId)) {
                userOrders.add(order);
            }
        }
        
        // 按创建时间倒序排列
        Collections.sort(userOrders, new Comparator<Order>() {
            @Override
            public int compare(Order o1, Order o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        
        return userOrders;
    }
    
    /**
     * 根据订单ID获取订单
     */
    public Order getOrderById(String orderId) {
        List<Order> orders = getAllOrders();
        for (Order order : orders) {
            if (TextUtils.equals(order.getOrderId(), orderId)) {
                return order;
            }
        }
        return null;
    }
    
    /**
     * 根据状态获取订单列表
     */
    public List<Order> getOrdersByStatus(String userId, Order.OrderStatus status) {
        List<Order> userOrders = getOrdersByUserId(userId);
        List<Order> filteredOrders = new ArrayList<>();
        
        for (Order order : userOrders) {
            if (order.getStatus() == status) {
                filteredOrders.add(order);
            }
        }
        
        return filteredOrders;
    }
    
    /**
     * 删除订单
     */
    public void deleteOrder(String orderId) {
        List<Order> orders = getAllOrders();
        orders.removeIf(order -> TextUtils.equals(order.getOrderId(), orderId));
        saveOrders(orders);
    }
    
    /**
     * 更新订单状态
     */
    public boolean updateOrderStatus(String orderId, Order.OrderStatus newStatus) {
        Order order = getOrderById(orderId);
        if (order != null) {
            order.setStatus(newStatus);
            
            // 根据状态设置相应的时间
            switch (newStatus) {
                case PAID:
                    order.setPayTime(new java.util.Date());
                    break;
                case SHIPPED:
                    order.setShipTime(new java.util.Date());
                    break;
                case DELIVERED:
                    order.setDeliveryTime(new java.util.Date());
                    break;
            }
            
            saveOrder(order);
            return true;
        }
        return false;
    }
    
    /**
     * 更新快递信息
     */
    public boolean updateTrackingInfo(String orderId, String trackingNumber, String trackingCompany) {
        Order order = getOrderById(orderId);
        if (order != null) {
            order.setTrackingNumber(trackingNumber);
            order.setTrackingCompany(trackingCompany);
            saveOrder(order);
            return true;
        }
        return false;
    }
    
    /**
     * 获取订单统计信息
     */
    public OrderStatistics getOrderStatistics(String userId) {
        List<Order> orders = getOrdersByUserId(userId);
        OrderStatistics statistics = new OrderStatistics();
        
        for (Order order : orders) {
            switch (order.getStatus()) {
                case PENDING:
                    statistics.pendingCount++;
                    break;
                case PAID:
                    statistics.paidCount++;
                    break;
                case SHIPPED:
                    statistics.shippedCount++;
                    break;
                case DELIVERED:
                    statistics.deliveredCount++;
                    break;
                case COMPLETED:
                    statistics.completedCount++;
                    break;
                case CANCELLED:
                    statistics.cancelledCount++;
                    break;
                case REFUNDING:
                    statistics.refundingCount++;
                    break;
                case REFUNDED:
                    statistics.refundedCount++;
                    break;
            }
        }
        
        return statistics;
    }
    
    /**
     * 清空所有订单数据
     */
    public void clearAllOrders() {
        preferences.edit().remove(KEY_ORDERS).apply();
    }
    
    /**
     * 保存订单列表到本地存储
     */
    private void saveOrders(List<Order> orders) {
        String json = gson.toJson(orders);
        preferences.edit().putString(KEY_ORDERS, json).apply();
    }
    
    /**
     * 订单统计信息
     */
    public static class OrderStatistics {
        public int pendingCount = 0;    // 待付款
        public int paidCount = 0;       // 已付款
        public int shippedCount = 0;    // 已发货
        public int deliveredCount = 0;  // 已送达
        public int completedCount = 0;  // 已完成
        public int cancelledCount = 0;  // 已取消
        public int refundingCount = 0;  // 退款中
        public int refundedCount = 0;   // 已退款
        
        public int getTotalCount() {
            return pendingCount + paidCount + shippedCount + deliveredCount + 
                   completedCount + cancelledCount + refundingCount + refundedCount;
        }
    }
} 